<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.wan888888.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use Common\Util\ConfigUtils;
use Common\Util\EncryUtils;
use Common\Util\UserUtils;
use User\Api\UserApi;

/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class PublicController extends \Think\Controller {

    /**
     * 后台用户登录
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function login($username = null, $password = null, $verify = null){
        if(IS_POST){
            /* 检测验证码 TODO: */
/*            if(!check_verify($verify)){
                $this->error('验证码输入错误！');
            }*/

            /* 调用UC登录接口登录 */
            $User = new UserApi;
            $uid = $User->login($username, $password);
            if(0 < $uid){ //UC登录成功
                /* 登录用户 */
                $Member = D('Member');
                if($Member->login($uid)){ //登录用户
                    //TODO:跳转到登录前页面
                    $this->success('登录成功！', U('Index/index'));
                } else {
                    $this->error($Member->getError());
                }

            } else { //登录失败
                switch($uid) {
                    case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
                    case -2: $error = '密码错误！'; break;
                    default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
                }
                $this->error($error);
            }
        } else {
            if(is_login()){
                $this->redirect('Index/index');
            }else{
                /* 读取数据库中的配置 */
                $config	=	S('DB_CONFIG_DATA');
                if(!$config){
                    $config	=	D('Config')->lists();
                    S('DB_CONFIG_DATA',$config);
                }
                C($config); //添加配置
                
                $this->display('login_new');
            }
        }
    }

    /* 退出登录 */
    public function logout(){
        if(is_login()){
            D('Member')->logout();
            session('[destroy]');
            $this->success('退出成功！', U('login'));
        } else {
            $this->redirect('login');
        }
    }

    public function verify(){
        $verify = new \Think\Verify(['imageW' => 350]);
        $verify->entry(1);
    }

    /**
     * 活动绑定管理严
     */
    public function activityBind()
    {
        $activity_id = I('activity_id');
        $activity_id or exit('参数错误');
        cookie('ACTIVITY_BIND_ACTIVITY_ID', $activity_id);


        $server_url = ConfigUtils::getConfig('SERVER_URL');
        $callback_url = $server_url . U('public/activityBindCallback');
        cookie(UserUtils::LAST_URL, $callback_url, ['prefix' => '']);

        $redirect_url = $server_url . U('home/wechat/url');
        header("Location: $redirect_url");
    }

    /**
     * 核销获取权限二维码回调
     */
    public function activityBindCallback()
    {
        $activity_id = qrcode_data_crypt(cookie('ACTIVITY_BIND_ACTIVITY_ID'), false);
        if ($activity_id === false) {
            echo "<script>alert('解密失败');window.close();</script>";
            exit;
        }

        $open_id = cookie(UserUtils::LOGIN_WEIXIN_OPENID_USER_COOKIE, '', ['prefix' => '']);
        $open_id and $open_id = EncryUtils::decrypt($open_id);

        if ($activity_id && $open_id) {
            $user_info = M('CrmWeixinMember')->where(['openid' => $open_id])->find();
            if ($user_info) {
                $where = [
                    'activity_id' => $activity_id,
                    'user_id' => $user_info['id'],
                    'isshow' => 1
                ];
                if (M('CrmActivityAdmin')->where($where)->count() == 0) {
                    $insert = ['createdate' => time(), 'activity_id' => $activity_id, 'user_id' => $user_info['id']];
                    M('CrmActivityAdmin')->add($insert);
                }
                echo "<script>alert('操作成功');window.close();</script>";
                return;
            }
        }

        echo "<script>alert('出错了');window.close();</script>";
    }


    /**
     * 核销获取权限二维码
     */
    public function writeOffBind()
    {
        $rule_id = I('rule_id');
        $rule_id or exit('参数错误');
        cookie('WRITE_OFF_BIND_RULE_ID', $rule_id);


        $server_url = ConfigUtils::getConfig('SERVER_URL');
        $callback_url = $server_url . U('public/writeOffBindCallback');
        cookie(UserUtils::LAST_URL, $callback_url, ['prefix' => '']);

        $redirect_url = $server_url . U('home/wechat/url');
        header("Location: $redirect_url");
    }

    /**
     * 核销获取权限二维码回调
     */
    public function writeOffBindCallback()
    {
        $rule_id = qrcode_data_crypt(cookie('WRITE_OFF_BIND_RULE_ID'), false);
        if ($rule_id === false) {
            echo "<script>alert('解密失败');window.close();</script>";
            exit;
        }

        $open_id = cookie(UserUtils::LOGIN_WEIXIN_OPENID_USER_COOKIE, '', ['prefix' => '']);
        $open_id and $open_id = EncryUtils::decrypt($open_id);

        if ($rule_id && $open_id) {
            $user_info = M('CrmWeixinMember')->where(['openid' => $open_id])->find();
            if ($user_info) {
                $where = [
                    'right_exchange_id' => $rule_id,
                    'weixin_member_id' => $user_info['id'],
                    'isshow' => 1
                ];
                if (M('CrmRightExchangeUser')->where($where)->count() > 0) {
                    echo "<script>alert('已获取过权限');window.close();</script>";
                    return;
                } else {
                    $insert = ['createdate' => time(), 'right_exchange_id' => $rule_id, 'weixin_member_id' => $user_info['id']];
                    M('CrmRightExchangeUser')->add($insert);
                    echo "<script>alert('获取核销权限成功');window.close();</script>";
                    return;
                }
            }
        }

        echo "<script>alert('出错了');window.close();</script>";
    }
}
